use crate::{components::{download_xlsx_file_with_url, upload_file::UploadFile}, shhr::{del_home_visit_file_by_fileid, del_home_visit_image_by_fileid, fetch_flow_run_step, update_home_visit_fileid_to_user, update_home_visit_image_fileid_to_user}};
use icondata as i;
use leptos::{prelude::*, task::spawn_local};
use leptos_icons::*;
use shq_common::prelude::User;
use shq_web_controls::{use_message, MessageOptions, MessageVariant, ToastPosition, ToasterProvider};
use thaw_utils::ArcOneCallback;

#[component]
pub fn HomeVisitFile(
    emnm: RwSignal<Option<String>>,
    emid: RwSignal<Option<u32>>,
    frid: RwSignal<u32>,
    home_visit_empl_id: RwSignal<Option<u32>>,
    home_visit_empl_fileid1: RwSignal<Option<u32>>,
    home_visit_empl_fileid2: RwSignal<Option<u32>>,
) -> impl IntoView {
    let mess = use_message();
    // 添加 Accordion 状态控制
    let open_pdf = RwSignal::new(true);
    let open_image = RwSignal::new(false);

    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let userid = curr_user.with(|u| u.as_ref().map(|u| u.id)).unwrap();

    let stepids = Resource::new(
        move || frid.get(),
        move |frid| async move{ 
            let stepid = fetch_flow_run_step(frid,userid).await;
            stepid
         }
    );
    view! {
        <Suspense fallback=|| view! { <progress class="progress"></progress> }>
            {move || {
                if let Some(name) = emnm.get() {
                    let display_name = if name.is_empty() {
                        "未选择用户".to_string()
                    } else {
                        name
                    };
                    let display_name_clone = display_name.clone();
                    let display_name_impoprt = display_name.clone();

                    //导入模块的展示
                    let showImportModel = RwSignal::new(false);
                    let showImportImageModel = RwSignal::new(false);
                    let flieid = RwSignal::new(0u64);
                    let image_flieid = RwSignal::new(0u64);
                    //导入后的回调
                    let on_upload = ArcOneCallback::new(
                        move |fileId: Vec<u64>| {
                            if fileId.len() > 0 {
                                flieid.set(fileId[0]);
                                home_visit_empl_fileid1.set(Some(fileId[0] as u32));
                                if let Some(id) = home_visit_empl_id.get() {
                                    spawn_local(async move{
                                        match update_home_visit_fileid_to_user(id, fileId).await {
                                            Ok(_) => {
                                                mess.create("导入成功", MessageVariant::Success, MessageOptions::default());
                                                showImportModel.set(false);
                                            }
                                            Err(e) => {
                                                mess.create(
                                                    format!("导入失败：{}", e),
                                                    MessageVariant::Error,
                                                    MessageOptions::default()
                                                );
                                            }
                                        };
                                    });
                                } else {
                                    // 处理home_visit_empl_id为None的情况
                                    mess.create("没有有效的员工ID", MessageVariant::Error, MessageOptions::default());
                                }
                            }
                        }
                    );
                    let image_on_upload = ArcOneCallback::new(
                        move |fileId: Vec<u64>| {
                            if fileId.len() > 0 {
                                image_flieid.set(fileId[0]);
                                home_visit_empl_fileid2.set(Some(fileId[0] as u32));
                                if let Some(id) = home_visit_empl_id.get() {
                                    spawn_local(async move{
                                        match update_home_visit_image_fileid_to_user(id, fileId).await {
                                            Ok(_) => {
                                                mess.create("导入成功", MessageVariant::Success, MessageOptions::default());
                                                showImportImageModel.set(false);
                                            }
                                            Err(e) => {
                                                mess.create(
                                                    format!("导入失败：{}", e),
                                                    MessageVariant::Error,
                                                    MessageOptions::default()
                                                );
                                            }
                                        };
                                    });
                                } else {
                                    // 处理home_visit_empl_id为None的情况
                                    mess.create("没有有效的员工ID", MessageVariant::Error, MessageOptions::default());
                                }
                            }
                        }
                    );
                    //导入模块的展示
                    let specialist_management = move || {
                        let on_upload=on_upload.clone();
                        if showImportModel.get() && stepids.get().and_then(|r| r.ok()) == Some(1) {
                            Some(view! {
                                <dialog id="data_import_modal" class="modal modal-open  z-50">
                                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                                        <button class="absolute right-2 top-2" on:click=move|_|{
                                            showImportModel.set(false);
                                        }>
                                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                                        </button>
                                        <h3 class="text-lg font-bold">导入家访表格</h3>
                                        <div class="p-2">
                                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                                <UploadFile accept=".pdf" on_upload/>
                                            </Suspense>
                                        </div>
                                    </div>
                                </dialog>
                            })
                        }else {
                            None
                        }
                    }; 
                    let specialist_management2 = move || {
                        let image_on_upload=image_on_upload.clone();
                        if showImportImageModel.get() && stepids.get().and_then(|r| r.ok()) == Some(1) {
                            Some(view! {
                                <dialog id="data_import_modal" class="modal modal-open  z-50">
                                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                                        <button class="absolute right-2 top-2" on:click=move|_|{
                                            showImportImageModel.set(false);
                                        }>
                                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                                        </button>
                                        <h3 class="text-lg font-bold">导入家访图片</h3>
                                        <div class="p-2">
                                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                                <UploadFile accept=".png" on_upload=image_on_upload/>
                                            </Suspense>
                                        </div>
                                    </div>
                                </dialog>
                            })
                        }else {
                            None
                        }
                    }; 
                    // 展示pdf内容
                    let path = match home_visit_empl_fileid1.get() {
                            Some(file_id) => format!("/binary_file/{}", file_id),
                            None => "/binary_file/default_file".to_string(), // 提供一个默认路径
                    };
                    let image_path = match home_visit_empl_fileid2.get() {
                            Some(image_id) => format!("/binary_file/{}", image_id),
                            None => "/binary_file/default_file".to_string(), // 提供一个默认路径
                    };

                    let download_template = Action::new(move |_| {
                        let uid = match emid.get() {
                            Some(id) => id,
                            None => 0, // 提供一个默认路径
                        };
                        let emnm2 = match emnm.get() {
                            Some(name) => name,
                            None => "".to_string(), // 提供一个默认路径
                        };
                        {
                            async move {
                                let path = format!("/export_import_home_visit_template/{}", uid);
                                let file_name = emnm2+"_员工家访情况记录表";
                                if let Err(err) = download_xlsx_file_with_url(&file_name,"xlsx", &path, None) {
                                    mess.create(err, MessageVariant::Error, MessageOptions::default());
                                }
                            }
                        }
                    });

                    //删除家访文件
                    let del_home_visit_file = Action::new(move|&(fileid,home_id):&(u32,u32)|{
                        async move{
                            match del_home_visit_file_by_fileid(fileid,home_id).await {
                                Ok(_) => {
                                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                                    home_visit_empl_fileid1.set(Some(0));
                                }
                                Err(e) => {
                                    mess.create(
                                        format!("删除失败：{}", e),
                                        MessageVariant::Error,
                                        MessageOptions::default()
                                    );
                                }
                            }
                        }
                    });
                    //删除家访图片
                    let del_home_visit_image = Action::new(move|&(fileid,home_id):&(u32,u32)|{
                        async move{
                            match del_home_visit_image_by_fileid(fileid,home_id).await {
                                Ok(_) => {
                                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                                    home_visit_empl_fileid2.set(Some(0));
                                }
                                Err(e) => {
                                    mess.create(
                                        format!("删除失败：{}", e),
                                        MessageVariant::Error,
                                        MessageOptions::default()
                                    );
                                }
                            }
                        }
                    });

                    view! {
                        <div class="flex flex-1 flex-col gap-4 p-4 overflow-hidden bg-white">
                            // 顶部信息与操作区
                            <div class="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
                                <div class="flex items-center">
                                    <h1 class="text-xl font-semibold text-gray-800">{format!("用户：{}", display_name)}</h1>
                                </div>
                                // 操作按钮
                                <div class="flex flex-wrap items-center gap-3">
                                    // <h3 class="text-base text-gray-600">{"家访表："}</h3>
                                    <button class="btn btn-primary transition-all hover:shadow-md"
                                        on:click=move |_| {
                                            if display_name_impoprt == "未选择用户" {
                                                mess.create(
                                                    "请选择要导入的用户！", 
                                                    MessageVariant::Success, 
                                                    MessageOptions::default()
                                                );
                                                return;
                                            }
                                            download_template.dispatch(());
                                        }
                                    >
                                        {"下载模板"}
                                    </button>
                                    <button 
                                        class="btn btn-primary transition-all hover:shadow-md" 
                                        on:click= move |_| {
                                            if display_name == "未选择用户" {
                                                mess.create(
                                                    "请选择要导入的用户！", 
                                                    MessageVariant::Success, 
                                                    MessageOptions::default()
                                                );
                                                return;
                                            }
                                            showImportModel.set(true);
                                        }
                                    >
                                        {"导入家访表"}
                                    </button>
                                    <button 
                                        class="btn btn-primary transition-all hover:shadow-md" 
                                        on:click= move |_| {
                                            if display_name_clone == "未选择用户" {
                                                mess.create(
                                                    "请选择要导入的用户！", 
                                                    MessageVariant::Success, 
                                                    MessageOptions::default()
                                                );
                                                return;
                                            }
                                            showImportImageModel.set(true);
                                        }
                                    >
                                        {"导入家访图片"}
                                    </button>
                                </div>
                            </div>
                            
                            <div class="flex-1 flex flex-col gap-4 overflow-auto">
                                // PDF Accordion
                                <div class="collapse collapse-arrow bg-base-100 border rounded-lg overflow-hidden">
                                    <input 
                                        type="checkbox" 
                                        checked=move || open_pdf.get()
                                        on:change=move |e| {
                                            let checked = event_target_checked(&e);
                                            open_pdf.set(checked);
                                            if checked {
                                                open_image.set(false);
                                            }
                                        }
                                    />
                                    <div class="collapse-title text-xl font-medium p-4 hover:bg-base-200 transition-colors flex items-center justify-between">
                                        <div class="flex items-center">
                                            <Icon 
                                                icon=i::AiFilePdfOutlined 
                                                width="20" 
                                                height="20"
                                            />
                                            {"家访表明细"}
                                        </div>
                                    </div>
                                    <div class="collapse-content p-0 transition-all duration-300 relative">
                                        <div class="w-full h-full min-h-[800px] bg-gray-50 flex items-center justify-center relative">
                                            <div class="absolute top-2 right-2 flex gap-2 z-50">
                                                <button class="btn btn-error btn-outline btn-sm bg-white/90 hover:bg-white transition-all shadow-md"
                                                    on:click=move |_| {
                                                        let file_id = match home_visit_empl_fileid1.get() {
                                                            Some(id) => id,
                                                            None => 0,
                                                        };
                                                        let home_id = match home_visit_empl_id.get() {
                                                            Some(id) => id,
                                                            None => 0,
                                                        };
                                                        if stepids.get().and_then(|r| r.ok()) == Some(1) {
                                                            del_home_visit_file.dispatch((file_id,home_id));
                                                        }
                                                    }
                                                >
                                                    <Icon icon=i::AiDeleteOutlined width="16" height="16"/>
                                                    {"删除"}
                                                </button>
                                                <button class="btn btn-primary btn-outline btn-sm bg-white/90 hover:bg-white transition-all shadow-md"
                                                    on:click=move |e| {
                                                        e.stop_propagation();
                                                        let pdf_element = document().get_element_by_id("pdf-viewer").expect("PDF viewer not found");
                                                        if let Ok(_) = pdf_element.request_fullscreen() {
                                                            log::info!("PDF进入全屏模式");
                                                        }
                                                    }
                                                >
                                                    <Icon icon=i::AiFullscreenOutlined width="16" height="16"/>
                                                    {"全屏"}
                                                </button>
                                            </div>
                                            <div class="w-full h-full min-h-[800px] relative z-10">
                                                <object 
                                                    id="pdf-viewer"
                                                    data={path.clone()} 
                                                    type="application/pdf" 
                                                    class="w-full h-full min-h-[800px] absolute inset-0"
                                                >
                                                    <div class="flex items-center justify-center h-full text-gray-500 text-lg">
                                                        "无法加载PDF文档"
                                                    </div>
                                                </object>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                // 图片 Accordion
                                <div class="collapse collapse-arrow bg-base-100 border rounded-lg overflow-hidden">
                                    <input 
                                        type="checkbox" 
                                        checked=move || open_image.get()
                                        on:change=move |e| {
                                            let checked = event_target_checked(&e);
                                            open_image.set(checked);
                                            if checked {
                                                open_pdf.set(false);
                                            }
                                        }
                                    />
                                    <div class="collapse-title text-xl font-medium p-4 hover:bg-base-200 transition-colors flex items-center justify-between">
                                        <div class="flex items-center">
                                            <Icon 
                                                icon=i::AiFileImageOutlined 
                                                width="20" 
                                                height="20"
                                            />
                                            {"家访图片明细"}
                                        </div>
                                    </div>
                                    <div class="collapse-content p-0 transition-all duration-300 relative">
                                        <div class="w-full h-full min-h-[400px] bg-gray-50 flex items-center justify-center">
                                            <div class="absolute top-2 right-2 flex gap-2 z-10">
                                                <button class="btn btn-error btn-outline btn-sm bg-white/80 hover:bg-white transition-all"
                                                    on:click=move |_| {
                                                        let file_id = match home_visit_empl_fileid2.get() {
                                                            Some(id) => id,
                                                            None => 0,
                                                        };
                                                        let home_id = match home_visit_empl_id.get() {
                                                            Some(id) => id,
                                                            None => 0,
                                                        };
                                                        if stepids.get().and_then(|r| r.ok()) == Some(1) {
                                                            del_home_visit_image.dispatch((file_id,home_id));
                                                        }
                                                    }
                                                >
                                                    <Icon icon=i::AiDeleteOutlined width="16" height="16"/>
                                                    {"删除"}
                                                </button>
                                                <button class="btn btn-primary btn-outline btn-sm bg-white/80 hover:bg-white transition-all"
                                                    on:click=move |e| {
                                                        e.stop_propagation();
                                                        let img_element = document().get_element_by_id("image-viewer").expect("Image viewer not found");
                                                        if let Ok(_) = img_element.request_fullscreen() {
                                                            log::info!("图片进入全屏模式");
                                                        }
                                                    }
                                                >
                                                    <Icon icon=i::AiFullscreenOutlined width="16" height="16"/>
                                                    {"全屏"}
                                                </button>
                                            </div>
                                            <img 
                                                id="image-viewer"
                                                src={image_path.clone()} 
                                                alt="家访图片" 
                                                class="max-w-full max-h-full object-contain cursor-zoom-in"
                                                on:click=move |e| {
                                                    e.stop_propagation();
                                                    let img_element = document().get_element_by_id("image-viewer").expect("Image viewer not found");
                                                    if let Ok(_) = img_element.request_fullscreen() {
                                                        log::info!("图片进入全屏模式");
                                                    }
                                                }
                                            />
                                        </div>
                                    </div>
                                </div>
                            </div>

                            // 提示信息容器
                            <ToasterProvider position=ToastPosition::TopStart>
                                {specialist_management}
                                {specialist_management2}
                            </ToasterProvider>
                        </div>
                    }.into_any()
                } else {
                    view! {
                        <div>
                            <p>{"Loading..."}</p>
                        </div>
                    }.into_any()
                }
            }}
        </Suspense>
    }
}
